package com.nnnu.wsnackshop.config;

import com.nnnu.wsnackshop.json.JacksonObjectMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    /**
     * 扩展spring mvc框架的消息转化器
     */
    @Override
    protected void extendMessageConverters(@NotNull List<HttpMessageConverter<?>> converters) {
        // 创建一个消息转换器
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).findFirst()
                .ifPresent(c -> ((MappingJackson2HttpMessageConverter) c).setObjectMapper(new JacksonObjectMapper()));
    }

    /**
     * 设置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
